package com.android.benbourahla.carmode.sms;

import java.util.Locale;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.widget.Toast;

import com.android.benbourahla.carmode.utils.Utils;

public class SMSService extends Service implements OnInitListener
{
	private TextToSpeech			smsTxtToSpeech	= null;
	private ContentResolver		cr							= null;
	private ServiceAsyncTask	locTask					= null;

	@Override
	public IBinder onBind(Intent arg0)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate()
	{
		smsTxtToSpeech = new TextToSpeech(this, this);
	}

	@Override
	public void onDestroy()
	{
		smsTxtToSpeech = null;
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		cr = getContentResolver();
		// Context c = this.getBaseContext();

		locTask = new ServiceAsyncTask();
		locTask.execute();

		return super.onStartCommand(intent, flags, startId);
	}

	private String formatMessage(final String message)
	{
		String str = message.toLowerCase();
		str = str.replaceAll("slt", "salut");
		str = str.replaceAll("cmt", "comment");
		str = str.replaceAll("bsx", "bisous");
		str = str.replaceAll("mdr", "mort de rire");
		str = str.replaceAll("a+", "a plus");
		str = str.replaceAll("2m1", "demain");
		str = str.replaceAll("bjr", "bonjour");
		str = str.replaceAll("bcp", "beaucoup");
		str = str.replaceAll("jtm", "je t'aime");
		str = str.replaceAll("svp", "S'il vous plait");
		str = str.replaceAll("stp", "S'il te plait");
		str = str.replaceAll("ptdr", "peter de rire");
		return str;
	}

	@Override
	public void onInit(int status)
	{
		if (status == TextToSpeech.SUCCESS)
		{
			int result = smsTxtToSpeech.setLanguage(Locale.FRANCE);
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED)
			{
				// Lanuage data is missing or the language is not supported.
				Log.e("SMSService", "Langue non disponible.");
			}

		}
	}

	private String findContactByPhone(String phoneNumber)
	{
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null,
				null, null);
		if (cur.getCount() > 0)
		{
			while (cur.moveToNext())
			{
				String id = cur.getString(cur
						.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cur.getString(cur
						.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				String hasPhone = cur.getString(cur
						.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
				if (Boolean.parseBoolean(hasPhone))
				{
					Cursor phones = getContentResolver().query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
							null, null);
					while (phones.moveToNext())
					{
						String phone = phones.getString(phones
								.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						if (phone.equals(phoneNumber) == true)
						{
							phones.close();
							return name;
						}
					}
					phones.close();
				}
			}
		}
		return "";
	}

	public class ServiceAsyncTask extends AsyncTask<Void, Void, Boolean>
	{

		@Override
		protected void onPostExecute(Boolean result)
		{
			Log.i("ApplicationService", "res = " + result);
			super.onPostExecute(result);
			this.cancel(true);
		}

		@Override
		protected Boolean doInBackground(Void... arg0)
		{
			SharedPreferences settings = getSharedPreferences(Utils.sharedName, 0);
			boolean isAppActivate = settings.getBoolean("IS_APP_ACTIVATED", false);
			while (isAppActivate == true)
			{
				String message = settings.getString("messageBody", "");
				String phone = settings.getString("phoneNumber", "");
				if (message.equals("") == false && phone.equals("") == false)
				{
					Utils.DisplayToast(getBaseContext(), message, Toast.LENGTH_LONG);
					String name = findContactByPhone(phone);
					if (name.equals("") == false)
					{
						Utils.DisplayToast(getBaseContext(),
								"Vous avez reçu un nouveau message de " + name + " qui dit : "
										+ message, Toast.LENGTH_LONG);
						smsTxtToSpeech.speak("Vous avez reçu un nouveau message de " + name
								+ " qui dit : " + formatMessage(message),
								TextToSpeech.QUEUE_FLUSH, null);
					}
					else
					{
						Utils.DisplayToast(getBaseContext(),
								"Vous avez reçu un nouveau message de " + phone + " qui dit : "
										+ message, Toast.LENGTH_LONG);
						smsTxtToSpeech.speak("Vous avez reçu un nouveau message de "
								+ phone + " qui dit : " + formatMessage(message),
								TextToSpeech.QUEUE_FLUSH, null);

					}
				}
			}
			return false;
		}
	}

}
